package com.iemes.controller.workcenter_model;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.NumberRuleFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.workcenter_model.NumberRuleService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;


/**
 * 
 */
@Controller
@RequestMapping("/workcenter_model/number_rule/")
public class NumberRuleController extends BaseController {
	
	@Inject
	private BaseMapper baseMapper;
		
	@Inject
	private NumberRuleService numberRuleService;
	
	private Logger log = Logger.getLogger(this.getClass());
	private String numberRuleManagerUrl = Common.BACKGROUND_PATH + "/workcenter_model/number_rule/number_rule_manager";

	//页面跳转
	@RequestMapping("number_rule_manager")
	public String Get_number_rule_manager_Url(Model model,HttpServletRequest request) throws Exception {
		model.addAttribute("res", findByRes());
		handlePageRes(model,request);
		return numberRuleManagerUrl;
	}
	
	/**
	 * 保存编号规则信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveNumberRule")
	@SystemLog(module="编号规则管理",methods="编号规则管理-保存编号规则")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String saveNumberRule() {
		NumberRuleFormMap numberRuleFormMap = getFormMap(NumberRuleFormMap.class);
		numberRuleFormMap.put("create_time", DateUtils.getStringDateTime());
		numberRuleFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		numberRuleFormMap.put("site_id", ShiroSecurityHelper.getSiteId());	
		numberRuleFormMap.put("current_number", numberRuleFormMap.getStr("base_number"));	
		setNumberExample(numberRuleFormMap);
		try {
			numberRuleService.saveNumberRule(numberRuleFormMap);	
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	

	/**
	 * 检索编号规则
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryNumberRule")
	public String queryNumberRule(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String numberRule = request.getParameter("number_rule");
		//1.查询编号规则的基本信息
		NumberRuleFormMap numberRuleFormMap = new NumberRuleFormMap();
		numberRuleFormMap.put("number_rule", numberRule);
		numberRuleFormMap.put("site_id", siteId);
		List<NumberRuleFormMap> listNumberRuleFormMap= baseMapper.findByNames(numberRuleFormMap);
		if (!ListUtils.isNotNull(listNumberRuleFormMap)) {
			String errMessage = "未检索到编号规则为：" + numberRule.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return numberRuleManagerUrl;
		}
		
		numberRuleFormMap = listNumberRuleFormMap.get(0);
		setNumberExample(numberRuleFormMap);
		model.addAttribute("numberRuleFormMap", numberRuleFormMap);					
		model.addAttribute("successMessage", "检索成功");
		
		handlePageRes(model,request);
		return numberRuleManagerUrl;
	}
	
	/**
	 * 删除编号规则
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delNumberRule")
	public String delNumberRule(Model model, HttpServletRequest request) {
		String numberRuleId = request.getParameter("number_rule_id");
		try {
			if (StringUtils.isEmpty(numberRuleId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			numberRuleService.delNumberRule(numberRuleId);
		} catch (BusinessException e) {
			String errMessage = e.getMessage();
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return numberRuleManagerUrl;
		}
		model.addAttribute("res", findByRes());
		model.addAttribute("successMessage", "删除编号规则成功");
		handlePageRes(model,request);
		return numberRuleManagerUrl;
	}
	
	private void setNumberExample(NumberRuleFormMap numberRuleFormMap) {
		// 编号生成规则:【前缀】+【时间戳(精确到秒)】+【数字(按规则增长,且每秒数字都从起点开始计数)】+【后缀】
		int totalNumberLen = 32;
	    Object obOl= numberRuleFormMap.get("order_length");
	    totalNumberLen = Integer.valueOf(obOl.toString());
		int numberTimestampLen = "19990101121212".length();
		String prefix = numberRuleFormMap.getStr("prefix");
		prefix = StringUtils.isEmpty(prefix) ? "" : prefix;
		String postfix = numberRuleFormMap.getStr("postfix");
		postfix = StringUtils.isEmpty(postfix) ? "" : postfix;
		int fixLen = (StringUtils.isEmpty(prefix)?0: prefix.length()) + (StringUtils.isEmpty(postfix)?0: postfix.length());
		int numberLen = totalNumberLen - numberTimestampLen - fixLen;
		String numberStr = "1";
		if (numberLen > 0) {
			numberStr = String.format("%0" + numberLen + "d", 1);
		}
		String numberExample = prefix + "19990101121212" + numberStr + postfix;
		numberRuleFormMap.put("number_example", numberExample);
	}

}